angular.module('myApp.carData')
.component("realDataComponent",{
    templateUrl:'car_data_module/real_data.html',
    css:'car_data_module/real_data.css',
    controller:'realDataCtl'
})
.controller('realDataCtl',function($scope, $http, $location, $state, $cookieStore){

    /********************初始化地图****************************/
    $scope.map = new BMap.Map("container");
    var point = new BMap.Point(116.404, 39.915);
    $scope.map.centerAndZoom(point, 10);

    //用来设置ICON,和marker相关
    $scope.Icon = new BMap.Icon('static/images/trail_map/origin_car.png', new BMap.Size(40, 23),{
        anchor: new BMap.Size(0, 0),
        imageOffset: new BMap.Size(0, 0)
    });

    $scope.lineStyle = {
        strokeColor: "blue",
            strokeWeight: 3,
        strokeOpacity: 0.5
    }
    /*************描述页面的整个信息******************/

    $scope.car_type = [
        {value:'1', name:'轿车'},
        {value:'2', name:'运输车'},
        {value:'3', name:'挖掘机'},
        {value:'4', name:'渣土车'},
        {value:'0', name:'其他'}
    ]

    $scope.haveData = false;

    //车辆的数据信息
    $scope.data = [];
    $scope.markerArray = [];
    //当前车辆的司机信息

    // $scope.driver;
    // $scope.have_driver = false;
    // $scope.currentCar = {
    //     location:'',
    //     status:'',
    //     oil:'',
    //     license:'',
    //     id: null
    // }

    $scope.car_list = false;

    $scope.showCarList=function(){
        $scope.car_list = !$scope.car_list;
    }

    setTimeout(function(){
        $("li").click(function(){
            var num = $(this).index();
            var carType = $scope.car_type[num-1].value;
            clearInterval($scope.intervalNum);
            console.log("/all/car_position" + "?" + "carType=" + carType)
            $scope.intervalNum = setInterval(PostMessage("/all/car_position" + "?" + "carType=" + carType),10000)
        })
    },0)

    //获取跳转页面所需要的参数
    $scope.Watch_trail = function(){
        if ($scope.pageAllInfo.havaCarData) {
            // console.log($scope.currentCar.id)
            // console.log($scope.currentCar.license)
            $state.go('trail_map', {
                    car_id: $scope.pageAllInfo.currentCarInfo.id,
                    car_num: $scope.pageAllInfo.currentCarInfo.car_num
                })
        }else{
            layer.open({
                title: '提示',
                content: '无法获取车辆轨迹'
            });
        }
    }

    // function get_location(latitude, longitude){

    //     var myGeo = new BMap.Geocoder();
    //     // 根据坐标得到地址描述
    //     myGeo.getLocation(new BMap.Point(longitude, latitude), function(result){
    //         if (result){
    //             $scope.currentCar.location = result.address;
    //             $scope.$apply()
    //         }else{
    //             layer.alert('获取位置失败')
    //         }
    //     });
    // }
    // $scope.allCarPoints = {};
    // function make_marker(data){
    //     for(let i=0; i< data.length; i++){
    //         //这里如果要设置不同颜色的图片,可以将数据的状态取出，然后设置
    //         let myIcon = new BMap.Icon('static/images/trail_map/origin_car.png', new BMap.Size(40, 23),{
    //             anchor: new BMap.Size(0, 0),
    //             imageOffset: new BMap.Size(0, 0)
    //         });

    //         let marker = new BMap.Marker(new BMap.Point(data[i].bd_longitude, data[i].bd_latitude), {icon: myIcon});

    //         var {car_id, bd_longitude, bd_latitude} = data;

    //         if(typeof $scope.allCarPoints[data.car_id] == undefined){
    //             $scope.allCarPoints[car_id] = [];
    //         }
    //         $scope.allCarPoints[car_id].push(new BMap.Point(data[i].bd_longitude, data[i].bd_latitude));

    //         if($scope.allCarPoints[car_id].length > 1){
    //             ponits = [ $scope.allCarPoints[car_id][length-2], $scope.allCarPoints[car_id][length-1] ];
    //             var polyline = new BMap.Polyline(ponits, {
    //                 strokeColor: "blue",
    //                 strokeWeight: 3,
    //                 strokeOpacity: 0.5
    //             });
    //             $scope.map.addOverlay(polyline);
    //         }

    //         marker.addEventListener('click', function(e){
    //             if($scope.markerArray.length > 0){
    //                 $scope.haveData = true;
    //                 for(let i=0; i < $scope.markerArray.length; i++){
    //                     if(e.target == $scope.markerArray[i].Mark){
    //                         //使用之前需要将内容清空
    //                         $scope.currentCar = {};

    //                         $scope.currentCar.status = $scope.markerArray[i].data.status;
    //                         $scope.currentCar.license = $scope.markerArray[i].data.car_num;
    //                         $scope.currentCar.oil = $scope.markerArray[i].data.oil;
    //                         get_location($scope.markerArray[i].data.bd_latitude, $scope.markerArray[i].data.bd_longitude);
    //                         $scope.currentCar.id =  $scope.markerArray[i].data.id;
    //                         $http.post(baseurl + "/get_driver_info", {car_id:$scope.markerArray[i].data.id}).then((res)=>{
    //                             console.log("打印当前车司机信息",res);
    //                             if(res.data.ret == 1){
    //                                 $scope.driver = {};
    //                                 $scope.driver = res.data.info[0];
    //                                 console.log("获取司机信息", $scope.driver);
    //                                 $scope.have_driver = true;
    //                             }else{
    //                                 $scope.driver = {};
    //                                 $scope.have_driver = false;
    //                                 layer.alert("获取司机信息失败,请稍后重试！！");
    //                             }
    //                         },(err)=>{
    //                             layer.alert("网络错误");
    //                         })
    //                     }
    //                 }
    //             }else{
    //                 $scope.haveData = false;
    //             }
    //         })

    //         $scope.markerArray.push({
    //             data:data[i],
    //             Mark:marker
    //         })
    //     }
    // }

    // function show_marker(markerArray){
    //     markerArray.forEach(function(item ,index, array){
    //         $scope.map.addOverlay(item.Mark)
    //     })
    // }

    // function remove_marker(markerArray){
    //     markerArray.forEach(function(item ,index, array){
    //         $scope.map.removeOverlay(item.Mark)
    //     })
    // }

    // function setMapCenter(latitude, longitude){
    //     $scope.map.setCenter(new BMap.Point( longitude, latitude ))
    // }

    // console.log("This is real")
    // $scope.initialized = false;

    // $scope.changeCar = function( item ){
    //     console.log(item);
    // }

    /**********************第一次获取所有车辆的数据*******************************/
    $scope.pageAllInfo = {
        havaCarData:false, //用来判断是否有数据
        carType:null,

        allCarData:{},     //用来存储所有的车辆数据
        allMarker:[],  //用来将allCarData中的车辆坐标点转换为marker
        allCarPoints:[], //用来将allCarData中的每辆车的轨迹点转为坐标点

        currentCarType:0,
        currentCarInfo:null,
        currentCarAddress:""
    };
    //1.选择车类型
    $scope.changeCar = function( item ){
        $scope.pageAllInfo.currentCarType = item.value;
        //2.将选择好的车类型传给PostMess函数执行
        PostMess("/all/car_position?cartype=", $scope.pageAllInfo.currentCarType);
    }
    //获取车辆位置函数
    function get_location(latitude, longitude){

        var myGeo = new BMap.Geocoder();
        // 根据坐标得到地址描述
        myGeo.getLocation(new BMap.Point(longitude, latitude), function(result){
            if (result){
                //将位置信息赋值给当前点击的车辆的currentCarAddress
                $scope.pageAllInfo.currentCarAddress = result.address;
                console.log( $scope.pageAllInfo.currentCarAddress )
                $scope.$apply();
            }else{
                layer.alert('获取位置失败');
            }
        });
    }
    //获取当前类型的所有车辆信息 传入接口地址 和 车类型
    function PostMess(url, type){
        $http.post(baseurl + url + type ).then((res)=>{
            console.log("执行PostMess 获取当前类型车辆的信息>>>",res)
            if(res.data.ret == 1){
                if(res.data.info.length == 0 || res.data.info == null){
                    //没有获取的该类型车辆信息数据
                    $scope.pageAllInfo.havaCarData = false;
                    layer.alert("没有该类型车辆信息和数据..");
                }else{
                    //将获取到的数据填充
                    $scope.pageAllInfo.havaCarData = true;
                    $scope.pageAllInfo.allCarData = res.data.info;//Array()
                    console.log("获取到的该类型的所有车辆的信息", $scope.pageAllInfo.allCarDat);
                    //删除地图上所有的以前的车辆图标marker  指定覆盖物
                    $scope.pageAllInfo.allMarker.forEach(function(item, index, array){
                        $scope.map.removeOverlay(item.marker);
                    });
                    //删除地图上所有的以前的车辆轨迹line  指定覆盖物
                    $scope.pageAllInfo.allCarPoints.forEach(function(item, index, array){
                        if( item.line != null ){
                            $scope.map.removeOverlay(item.line);
                    }
                    });
                    //使用allCarData中的点设置marker
                    makeMarker( $scope.pageAllInfo.allCarData );
                    makePointsAndLine( $scope.pageAllInfo.allCarData );

                    switchCarAsType($scope.pageAllInfo.currentCarType);

                    console.log( $scope.pageAllInfo.allMarker );
                    console.log( $scope.pageAllInfo.allCarPoints );


                }

            }
            else if(res.data.ret == -3){

                layer.alert("身份验证以过期,请重新登录");
                window.location.href = URL.baseurl +　'login.html';

            }
            else if(res.data.ret == -1){

                layer.msg(
                    "暂无车辆轨迹信息...",
                    {
                        icon:5,
                        time:3000
                    }
                )
            }

        },(err)=>{
            layer.alert("网络错误");
        })
    }
    /*
    * 输入为allCarData,输出为marker
    * */

    function makeMarker(data){

        for(let i=0; i < data.length; i++){
            //获取每辆车的车牌
            let car_num  = data[i].car_num;
            //获取每辆车的经纬度
            let longtitude = data[i].bd_longitude;
            let lantitude = data[i].bd_latitude;
            //根据坐标在地图上绘制当前车辆
            let point = new BMap.Point(longtitude, lantitude)
            let marker = new BMap.Marker(point, { icon: $scope.Icon });
            //为每辆车图标添加点击事件
            marker.addEventListener('click',function(e){
                //获取有关车辆信息的数据
                $scope.pageAllInfo.allMarker.forEach(function(item, index, array){
                    if( e.target == item.marker ){
                        console.log("here~~~");
                        console.log(item);
                        $scope.pageAllInfo.currentCarInfo=item.car_info;
                        console.log("当前点击车辆的信息", $scope.pageAllInfo.currentCarInfo);
                        // $scope.theClickedCarNum = item.car_num;
                        // $scope.theClickedDriverPic = item.driver_pic;
                        //获取司机信息
                        let lan = item.car_info.bd_latitude
                        let long = item.car_info.bd_longitude
                        get_location(lan, long);
                    }
                })

                console.log("you click me ")
            })

            let flag = $scope.pageAllInfo.allMarker.some( function(item, index, array){
                return item.car_num === car_num;
            } )
            if(!flag){
                $scope.pageAllInfo.allMarker.push({
                    car_num:car_num,
                    car_info:data[i],
                    marker:marker
                })
            }else{
                $scope.pageAllInfo.allMarker.forEach(function(item, index, array){
                    if( item.car_num == car_num ){
                        array[index].marker = marker;
                    }
                })
            }

        }
    }
    function makePointsAndLine(data){

        for(let i=0; i < data.length; i++){

            //找车辆的标志
            let car_num  = data[i].car_num;
            //提取每辆车中的坐标点
            let longtitude = data[i].bd_longitude;
            let lantitude = data[i].bd_latitude;
            let point = new BMap.Point(longtitude, lantitude);

            //$scope.pageAllInfo.allCarPoints是否存在car_num;
            let flag = $scope.pageAllInfo.allCarPoints.some(function(item, index, array){
                return item.car_num === car_num;
            });
            if( !flag ){
                $scope.pageAllInfo.allCarPoints.push({
                    car_info:data[i],
                    car_num: car_num,
                    points:[point],
                    line:null
                })
            }else{
                $scope.pageAllInfo.allCarPoints.forEach(function(item, index, array){
                    if(item.car_num == car_num ){
                        array[index].points.push( point );
                    }
                    item.line = new BMap.Polyline(point, $scope.lineStyle);
                });
            }
        }
    }
    //切换车辆类型 绘制车辆图标和轨迹
    function switchCarAsType(cartype = 2){
        console.log("************************");
        //为每个该类型的车绘制图标marker
        $scope.pageAllInfo.allMarker.forEach(function(item, index, array){
            if( item.car_info.cartype == cartype + "" ){
                $scope.map.addOverlay(item.marker);
            }

        });
        //为每个该类型的车绘制轨迹line
        $scope.pageAllInfo.allCarPoints.forEach(function(item, index, array){
            if( item.car_info.cartype == (cartype + "") ){
                if( item.line != null ){
                    $scope.map.addOverlay(item.line);
                }
                //设置中心点和缩放级别
                $scope.map.centerAndZoom( item.points[ item.points.length - 1 ], 12);
            }

        });
    }

    /*************************************************************/
    //PostMess("/all/car_position?cartype=2");

    function PostMessage(url){
        $http.post(baseurl + url).then((res)=>{
            console.log(res);
            if(res.data.ret === 1){
                //判断是否有车辆数据
                console.log(res.data.info)
                if(res.data.info.length == 0 || res.data.info == null){
                    $scope.haveData = false;
                    layer.alert("当前没有车辆信息,请稍后重试！！");
                }else{
                    $scope.haveData = true;
                    $scope.data = res.data.info;

                    if(!$scope.initialized){
                        setMapCenter($scope.data[0].bd_latitude, $scope.data[0].bd_longitude);
                        $scope.initialized = !$scope.initialized;
                    }

                    remove_marker($scope.markerArray);
                    $scope.markerArray = [];

                    make_marker($scope.data);
                    show_marker($scope.markerArray);

                    //设置当前车辆的信息
                    $scope.currentCar.status = $scope.data[0].status;
                    $scope.currentCar.oil = $scope.data[0].oil;
                    $scope.currentCar.license = $scope.data[0].car_num;
                    get_location($scope.data[0].bd_latitude, $scope.data[0].bd_longitude);
                    $scope.currentCar.id = $scope.data[0].id
                    //产生车辆标记之前需要将司机的信息获取到
                    $http.post(baseurl + "/get_driver_info", {car_id:$scope.data[0].id}).then((res)=>{
                        if(res.data.ret == 1){
                            $scope.driver = res.data.info[0];
                            $scope.have_driver = true;
                        }else{
                            $scope.have_driver = false;
                            layer.alert("获取司机信息失败,请稍后重试！！");
                        }
                    },(err)=>{
                        $scope.haveData = false;
                        layer.alert("网络错误");
                    })
                }
            }else if( res.data.ret == -3 ){
                layer.alert("身份验证过期，请重新登录");
                window.location.href = URL.baseurl +　'login.html';
            }else if(res.data.ret===-1){
                layer.msg(
                    "暂无车辆轨迹信息..",
                    {
                        icon:5,
                        time:3000
                    }
                )
            }
        },(err)=>{
            layer.alert("网络错误")
        })
    }
    //$scope.intervalNum = setInterval(PostMessage("/all/car_position"), 10000);
    $scope.$on("$destroy", function(){
        clearInterval($scope.intervalNum)
    });
    //清除trail_map页面已缓存的trail_car_id 和 trail_car_num
    $cookieStore.remove('trail_car_id');
    $cookieStore.remove('trail_car_num');
});